import pyautogui
import time
import matplotlib.pyplot as plt
from pynput import keyboard

# 设置Matplotlib后端为TkAgg
import matplotlib
matplotlib.use('TkAgg')

# 定义像素点坐标
x, y = 2380, 1180

# 定义监测时间（秒）
monitor_time = 30
# 初始化RGB值列表
red_values = []
green_values = []
blue_values = []

# 标记是否开始监测
start_monitoring = False

def on_press(key):
    global start_monitoring
    try:
        if key.char == 'g':
            print("G键按下，开始监测...")
            start_monitoring = True
            return False  # 停止监听
    except AttributeError:
        pass

def monitor_pixel():
    global start_monitoring
    # 监听键盘事件
    with keyboard.Listener(on_press=on_press) as listener:
        listener.join()

    # 记录开始时间
    start_time = time.time()

    # 循环监测RGB值
    while time.time() - start_time < monitor_time and start_monitoring:
        # 获取像素点的RGB值
        r, g, b = pyautogui.pixel(x, y)

        # 将RGB值添加到列表中
        red_values.append(r)
        green_values.append(g)
        blue_values.append(b)

        # 等待0.1秒再获取下一个RGB值
        time.sleep(0.01)

    # 创建时间轴
    time_axis = [i * 0.1 for i in range(len(red_values))]

    # 绘制RGB曲线
    plt.figure(figsize=(10, 6))
    plt.plot(time_axis, red_values, label='Red', color='red')
    plt.plot(time_axis, green_values, label='Green', color='green')
    plt.plot(time_axis, blue_values, label='Blue', color='blue')

    # 添加图例和标签
    plt.title('RGB Values Over Time')
    plt.xlabel('Time (seconds)')
    plt.ylabel('RGB Value')
    plt.legend()

    # 显示图形
    plt.show()

if __name__ == "__main__":
    monitor_pixel()
